package core;

import database.User;
import database.UserDb;
import utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by jimmyhsu on 2016/12/23.
 */
public class ChangePassword extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oldPwd = req.getParameter("inputOldPwd");
        String newPwd = req.getParameter("inputPassword");
        String type = req.getParameter("type");
        String userId = (String) req.getSession().getAttribute("username");
        boolean toAdmin = !StringUtils.isEmpty(type) && type.equals("superadmin");
        resp.setContentType("text/html;charset=gb2312");
        PrintWriter writer = resp.getWriter();
        if (StringUtils.isEmpty(userId)) {
            gotoLogin(writer, toAdmin, false);
        }
        User user = UserDb.selectUserById(userId);
        if (user.getPassword().equals(oldPwd)) {
            UserDb.updateStudentPassword(userId, newPwd);
            req.getSession().invalidate();
            gotoLogin(writer, toAdmin, false);
        } else {
            gotoLogin(writer, toAdmin, true);
        }
    }

    private void gotoLogin(PrintWriter writer, boolean toAdmin, boolean wrongPwd) {
        if (!toAdmin) {
            if (wrongPwd) {
                writer.print("<script>location.href='../view/Student/changePassword.jsp?wrong=true';</script>");
            } else {
                writer.print("<script>location.href='../view/Student/login.html';</script>");
            }
        } else {
            if (wrongPwd) {
                writer.print("<script>location.href='../view/Admin/changePassword.jsp?wrong=true';</script>");
            } else {
                writer.print("<script>location.href='../view/Admin/login.html';</script>");
            }
        }
    }
}
